package com.yun.util.yun.utils.file;


import org.springframework.core.env.Environment;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @Description: 文件工具类
*/
public class FileTasksUtils {



    public static String createCollectFile(Environment environment, String neName, String instId, String cmdGrpId) throws Exception {
        String collectFileDir = environment.getProperty("backUpFilepath");

        String fileName = instId  + "_" + neName  + "_" + cmdGrpId + ".txt";
        File dir = new File(collectFileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String realPath = dir.getAbsolutePath().replace("\\", "/");
        collectFileDir = collectFileDir.replace("\\", "/");
        String prefix = collectFileDir.substring(0, 1);
        if (!realPath.startsWith(prefix)) {
            throw new RuntimeException("[odm-server]所在的服务器不存在UCMP配置项[backUpFilepath]配置的目录");
        }
        String dateDir = getCurrentTime("yyyy-MM-dd");
        dir = new File(dir, dateDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return getFileFullPath(dir.getAbsolutePath(), fileName);
    }

    private static String getCurrentTime(String formatPattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
        return sdf.format(new Date());
    }

    private static String getFileFullPath(String dir, String fileName) {
        File targetFile = new File(dir, fileName);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException("创建文件[" + fileName + "]异常:" + e.getMessage());
            }
        }
        String path = targetFile.getPath().replace("\\", "/");
        return path;
    }
}
